// pages/publish/publish.js
var service_user = require("../../service/user.js")
var service_common = require("../../service/common.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image_array: [],
    textarea: '',
    textareaNum: 0,
    VideoSrc: [],
    filePath: '',
    arr: []
  },
  /*
  *设置当前多行文本框输入的字数
  */
  textareaNum: function (e) {
    this.setData({
      textareaNum: e.detail.cursor,
      textarea: e.detail.value
    })
  },

  /**
   * 切换当前的发布类型
   * */
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },


  /*跳转开代理*/
  gotokaidaili: function (e) {
    add_form_id(e.detail.formId)
    wx.navigateTo({
      url: '/pages/kaidaili/kaidaili',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '发布您的要求',
    });
    service_user.getTypeList2(this.getTypeList);
  },
  getTypeList: function (res) {
    if (res.data.code == 0) {
      var that = this;
      var typeArray = [];
      for (var i = 0; i < res.data.data.length; i++) {
        typeArray.push(res.data.data[i].type)
      }
      that.setData({
        typeArray: typeArray
      })
    }
  },
  uploadVideo: function () {
    this.setData({
      modalShow: '',
      image_array: []
    })
    var temp = [];
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 20,
      camera: 'back',
      success: function (res) {
        if (res.duration > 20) {
          wx.showToast({
            title: '视频时间不能大于20秒',
            image: '../../image/wrong.png',
            duration: 500
          })
        } else {
          temp = res.tempFilePath;
          that.setData({
            VideoSrc: res.tempFilePath
          })
        }

      },
      complete: res => {
        var filePath = temp;
        console.log('filePath:' + filePath)
        wx.uploadFile({
          url: getApp().globalData.API_Base_URL + "/uri/topic/upload",
          filePath: filePath,
          name: "file",
          formData: {
            'version': getApp().globalData.version,
            'openid': getApp().globalData.openid
          },
          success: function (res) {
            console.log('res的结果' + res)
            var data_json = JSON.parse(res.data);
            var url = data_json.data;
            console.log("url", url, data_json);
            var old_files = that.data.filePath;
            that.setData({
              filePath: old_files + ',' + url
            })
            wx.hideLoading()
            if (res.statusCode == 200) {

              var data = JSON.parse(res.data);

            } else {
              wx.showModal({
                title: '提示',
                content: '上传失败，请重试',
                showCancel: false,
                success: res => {

                }
              })
            }
          }
        })

      },

    })
  },
  showUpload: function () {
    this.setData({
      modalShow: 'show'
    })
  },
  modalHide: function () {
    this.setData({
      modalShow: ''
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 上传图片
   */
  uploadImage: function () {
    this.setData({
      modalShow: '',
      VideoSrc: []
    })
    var that = this
    var temp = [];
    var image_array = this.data.image_array;
    wx.chooseImage({
      count: (6 - this.data.image_array.length),
      sizeType: ['compressed'],
      success: function (res) {
        temp = res.tempFilePaths;
        for (var i = 0; i < temp.length; i++) {
          image_array.push(temp[i]);
        }
        that.setData({
          image_array: image_array
        })
      },
      complete: res => {
        if (temp.length > 0) {
          wx.showLoading({
            title: '上传中...',
          })
        }
        for (var i = 0; i < temp.length; i++) {

          var filePath = temp[i];
          console.log('filePath:' + filePath);
          wx.uploadFile({
            url: getApp().globalData.API_Base_URL + "/api/topic/upload",
            filePath: filePath,
            name: "file",
            formData: {
              'version': getApp().globalData.version,
              'openid': getApp().globalData.openid,
              "token": wx.getStorageSync('token__'),
              "token_key": wx.getStorageSync('token_key')
            },
            success: function (res) {
              wx.hideLoading()
              console.log(JSON.parse(res.data).code)
              if (JSON.parse(res.data).code == 0) {
                wx.hideLoading()
                var data_json = JSON.parse(res.data);
                var url = data_json.data;
                that.data.arr.push(url)
                var old_files = that.data.filePath;
                that.setData({
                  filePath: ',' + that.data.arr.toString(),
                  arr: that.data.arr
                })
                console.log(that.data.arr)
                wx.hideLoading()
                if (res.statusCode == 200) {
                  var str = JSON.parse(res.data);


                } else {
                  wx.showModal({
                    title: '提示',
                    content: '上传失败，请重试',
                    showCancel: false,
                    success: res => {
                    }
                  })
                }
              } else {
                var res = JSON.parse(res.data)
                console.log(res.data)
                wx.showModal({
                  title: '提示',
                  content: res.message,
                })
              }
            }
          })
        }
      }
    })
  },

  /**
   * 图片预览
   */
  showPhoto: function (e) {
    var id = e.currentTarget.id;
    var array = [];
    for (var i = 0; i < this.data.image_array.length; i++) {
      array[i] = this.data.image_array[i];
    }
    wx.previewImage({
      current: array[id],
      urls: array
    })
  },
  /**
   * 删除图片
   */
  deleteImage: function (e) {
    // var str = this.data.filePath.substring(1, this.data.filePath.length)
    // var filePath = str.split(',')
    // console.log(that.data.arr)
    var id = e.currentTarget.id
    var that = this;
    console.log(id)
    var image_array = this.data.image_array;
    that.data.arr.splice(id, 1)
    console.log(that.data.arr)
    image_array.splice(id, 1);
    this.setData({
      image_array: image_array,
      filePath: ',' + that.data.arr.toString(),
      arr: that.data.arr
    })
  },
  /**
   * 发布万人圈
   */
  issue: function (e) {
    var that = this;
    add_form_id(e.detail.formId);
    var file = "";
    var content = this.data.textarea;
    console.log(that.data.filePath)
    if (this.data.image_array.length == 0 && this.data.VideoSrc.length != 0) {
      console.log(1)
      file = this.data.filePath;
    }
    console.log(this.data.image_array)
    if (this.data.image_array.length != 0 && this.data.VideoSrc.length == 0) {
      var image = this.data.image_array;
      file = that.data.filePath
    }

    console.log('content内容' + content)
    console.log(file);
    var Type = this.data.typeArray[this.data.index];

    if (Type == undefined || Type == "" || Type.length == 0) {
      wx.showToast({
        title: '请选择分类',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else {
      service_user.setWanrenquan(content, file, Type, this.wanrenquan);
    }

  },
  wanrenquan: function (res) {
    console.log(res)
    
    if(res.data.code==0){
      service_common.fetchData(
        service_common.getUrl("user.sysconfig"), {
          openid: getApp().globalData.userInfo.openid
        },
        (res) => {
          console.log(res)
          if (res.data.code == 0) {
            if (parseFloat(res.data.data.topic_money) > 0) {//付费
              wx.requestPayment({
                timeStamp: res.data.data.timeStamp,
                nonceStr: res.data.data.nonceStr,
                package: res.data.data.package,
                signType: res.data.data.signType,
                paySign: res.data.data.paySign,
                success(res) {
                  wx.showToast({
                    title: '发布成功',
                    icon: 'none'
                  })
                  setTimeout(() => {
                    wx.navigateBack()
                  }, 2000)
                },
                fail(ress) {
                  wx.showToast({
                    title: '发布失败',
                    icon: 'none'
                  })
                }
              })
            } else {
              wx.showToast({
                title: '发布成功',
                icon: 'none'
              })
              setTimeout(() => {
                wx.navigateBack()
              }, 2000)
            }
          }
        })
     
    }else{
      if (res.data.code == 21004){
        wx.showModal({
          title: '提示',
          content: '需要前去下载APP',
          confirmText: "前往",
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/aApp/aApp',
              })
            }
          }
        })
      }else{
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
     
    }
    // if (res.data.code == 0) {
    //   wx.showModal({
    //     title: '提示',
    //     content: res.data.message,
    //     success: function (res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定')
    //         wx.navigateBack()
    //       } else if (res.cancel) {
    //         console.log('用户点击取消')
    //         wx.navigateBack()
    //       }
    //     }
    //   })

    // } else {
    //   console.log()
    //   if (res.data.message == "用户权限不足") {
    //     wx.showModal({
    //       title: '提示',
    //       content: res.data.message,
    //       success: function (res) {
    //         if (res.confirm) {
    //           console.log('用户点击确定')
    //           wx.navigateBack()
    //         } else if (res.cancel) {
    //           console.log('用户点击取消')
    //           wx.navigateBack()
    //         }
    //       }
    //     })
    //   } else {
    //     wx.showModal({
    //       title: '提示',
    //       content: res.data.message,
    //       success: function (res) {
    //         if (res.confirm) {
    //           console.log('用户点击确定')
    //           wx.navigateBack()
    //         } else if (res.cancel) {
    //           console.log('用户点击取消')
    //           wx.navigateBack()
    //         }
    //       }
    //     })
    //   }

    // }

  },

  gotokaidaili: function (e) {
    add_form_id(e.detail.formId)
    wx.navigateTo({
      url: '/pages/kaidaili/kaidaili',
    })
  }
})
//添加form_id
function add_form_id(form_id) {
  service_user.addFormId(form_id);
}